package com.yhcrt.service;

import java.util.*;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import com.alibaba.druid.support.json.JSONUtils;
import com.yhcrt.entiy.*;
import com.yhcrt.utils.JsonUtils;
import com.yhcrt.utils.StringUtils;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import com.yhcrt.dao.DaoSupport;
import com.yhcrt.utils.Constants;
import com.yhcrt.utils.GetPinyin;

/**
 * TODO
 * @author fk
 * 2021年10月14日
 */
@Service("MatchService")
public class MatchService {

	@Resource
	private DaoSupport dao;

	/**
	 * @Description: 查詢项目下的分组  -------------------v2
	 * @param cid
	 * @return List<Group>
	 */
	@SuppressWarnings("unchecked")
	public List<Group> findGroup(Integer pid) {
		List<Group> list = null;
		try {
			Map<String, Integer> paramMap = new HashMap<>();
			paramMap.put("pid", pid);
			paramMap.put("matchId", Constants.matchId);
			list = (List<Group>) dao.findForList("GroupMapper.findGroup", paramMap);
		} catch (Exception e) {
			e.printStackTrace();
			list = new ArrayList<>();
		}

		return list;
	}

	/**
	 * @Description:查询所有项目并首字母大写分组排序  -------------------v2
	 * @param pid
	 * @return Map<String,List<Group>>
	 */
	@SuppressWarnings("unchecked")
//	@Cacheable(value="groupCache", key="'group1'+#pid")
	public Map<String, Object> findPGroup(Integer pid) {
		Map<String, Object>  returnMap = new HashMap<>();
		try {
			Map<String, Object> paramMap = new HashMap<>();
			paramMap.put("pid", pid);
			paramMap.put("classType", "B");
			paramMap.put("matchId", Constants.matchId);
			List<Group> list1 = (List<Group>) dao.findForList("GroupMapper.findGroup", paramMap);

			if(list1.size()==0){
				paramMap.put("classType", "C");
				List<Group> list2 = (List<Group>) dao.findForList("GroupMapper.findGroup", paramMap);
				Map<String, List<Group>> pGroups =  menuFormatChar(list2);
				returnMap.put("num", 1);
				returnMap.put("pGroups", pGroups);
			}else{
				returnMap.put("num", 2);
				Map<String, List<Group>> pGroups = menuFormat(list1);
				returnMap.put("pGroups", pGroups);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return returnMap;
	}
	/**
	 *
	 * @Description:首字母大写分组排序    -------------------v2
	 * @param list
	 * @return Map<String,List<Group>>
	 */
	private Map<String, List<Group>> menuFormatChar(List<Group> list){
		Map<String, List<Group>> map = new  TreeMap<String, List<Group>>(
				new Comparator<String>() {
		        public int compare(String o1, String o2) {
		           return o1.compareTo(o2);
		        }
		});
		for (Group group : list) {
			String key = GetPinyin.getPinYinFirstHeadChar(group.getName());
			if(map.containsKey(key)){
				map.get(key).add(group);
			}else{
				List<Group> list1 = new ArrayList<>();
				list1.add(group);
				map.put(key, list1);
			}
		}
		return map;
	}
	/**
	 *
	 * @Description:分组排序   -------------------v2
	 * @param list
	 * @return Map<String,List<Group>>
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	private Map<String, List<Group>> menuFormat(List<Group> list) throws Exception{
		Map<String, List<Group>> map = new  LinkedHashMap<>();
		Map<String, Object> paramMap = new HashMap<>();
		paramMap.put("classType", "C");
		paramMap.put("matchId", Constants.matchId);
		for (Group g : list) {
			paramMap.put("pid", g.getCid());
			List<Group> list2 = (List<Group>) dao.findForList("GroupMapper.findGroup", paramMap);
			map.put(g.getName(), list2);
		}
		return map;
	}





	/**
	 * @Description: 查询组别下的时间节点    -------------------v2
	 * @param cid
	 * @return List<String>
	 */
	@SuppressWarnings("unchecked")
	public List<String> findGroupTime(Integer gid,Integer fid,String type) {
		List<String> list = null;
		try {
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("gid", gid);
			param.put("fid", fid);
			if (StringUtils.isNotEmpty(type)) {
				param.put("type", type);
			}else {
				param.put("type", "D");			//针对群众体育等默认用D即 e.PARENT_ID=#{fid}
			}
			param.put("matchId", Constants.matchId);
			list = (List<String>) dao.findForList("MatchMapper.findGroupTime", param);
		} catch (Exception e) {
			e.printStackTrace();
			list = new ArrayList<>();
		}
		return list;
	}

	@SuppressWarnings("unchecked")
	public List<Match> findProject(Integer cid) {   //查询项目下的小项  -------------------v2
		List<Match> list = null;
		try {
			Map<String, Object> map = new HashMap<>();
			map.put("cid", cid);
			map.put("matchId", Constants.matchId);
			list = (List<Match>) dao.findForList("MatchMapper.findProject", map);
		} catch (Exception e) {
			e.printStackTrace();
			list = new ArrayList<>();
		}
		return list;
	}

	/**
	 * @Description: 查询组别下的项目信息  -------------------v2
	 * @param cid
	 * @return List<Match>
	 */
	@SuppressWarnings("unchecked")
	public List<Match> findMatch(Integer gid,Integer fid,String type) {
		List<Match> list = null;
		try {
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("gid", gid);
			param.put("fid", fid);
			param.put("type", type);
			param.put("matchId", Constants.matchId);
			list = (List<Match>) dao.findForList("MatchMapper.findMatch", param);
			System.out.println("==========1================---------" + list.size());
			if(list.size()==0){
				return list;
			}
			System.out.println(JsonUtils.objectToJson(list.get(0)));
			for(Match match : list) {
				match.setClassAllName(Constants.getNameByCode(match.getClassCode(), 1));
			}
			System.out.println("==========2================---------" + list.size());
			System.out.println(JsonUtils.objectToJson(list.get(0)));
		} catch (Exception e) {
			e.printStackTrace();
			list = new ArrayList<>();
		}
		return list;
	}
	/**
	 *
	 * @Description: 查询每天参赛信息
	 * @param day
	 * @return List<Match>
	 */
	@SuppressWarnings("unchecked")
	public List<Match> findMatchByParam(String day,Integer cid) {

		Map<String, Object> map = new HashMap<>();
		map.put("day", day);
		map.put("cid", cid);
		map.put("matchId", Constants.matchId);
		List<Match> list = null;
		try {
			list = (List<Match>) dao.findForList("MatchMapper.findMatchByParam",map);
			for(Match match : list) {
				match.setClassAllName(Constants.getNameByCode(match.getClassCode(), 1));
			}
		} catch (Exception e) {
			e.printStackTrace();
			list = new ArrayList<>();
		}
		return list;
	}
	/**
	 *
	 * @Description: 查询每天项目
	 * @param day
	 * @return List<Match>
	 */
	@SuppressWarnings("unchecked")
	public List<Match> findMatchByTime(String day,Integer pid) {
		List<Match> list = null;
		try {
			Map<String, Object> map = new HashMap<>();
			map.put("day", day);
			map.put("pid", pid);
			map.put("matchId", Constants.matchId);
			list = (List<Match>) dao.findForList("MatchMapper.findMatchByTime",map);
			for(Match match : list) {
				match.setClassAllName(Constants.getNameByCode(match.getClassCode(), 1));
			}
		} catch (Exception e) {
			e.printStackTrace();
			list = new ArrayList<>();
		}
		return list;
	}
	/**
	 *
	 * @Description: 查询竞赛项目成绩名次     -------------------v2
	 * @param pid
	 * @return List<Scores>
	 */
	@SuppressWarnings("unchecked")
	public List<Scores> findMatchInfo(Integer pid) {
		List<Scores> list = null;
		try {
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("pid", pid);
			param.put("matchId", Constants.matchId);
			list = (List<Scores>) dao.findForList("MatchMapper.findMatchInfo", param);
		} catch (Exception e) {
			e.printStackTrace();
			list = new ArrayList<>();
		}
		return list;
	}
	public List<Scores> findMatchInfoForzdxs(String classAllName) {
		List<Scores> list = null;
		try {
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("classAllName", classAllName);
			param.put("matchId", Constants.matchId);
			list = (List<Scores>) dao.findForList("MatchMapper.findMatchInfoForzdxs", param);
		} catch (Exception e) {
			e.printStackTrace();
			list = new ArrayList<>();
		}
		return list;

	}
	/**
	 *
	 * @Description: 查询竞赛项目下的运动员        -------------------v2
	 * @param cid
	 * @return List<AthleteInfo>
	 */
	@SuppressWarnings("unchecked")
	public List<AthleteInfo> findAthleteList(Integer cid){
		List<AthleteInfo> list = null;
		try {
			List<String> athleteIdsList = (List<String>)dao.findForList("AthleteInfoMapper.findAthleteIdsFromSignup", cid);
			List<String> athleteIdList = athleteIdsList.stream().map(b-> Arrays.asList(StringUtils.split(b, ','))).reduce(new ArrayList<>(), (all, item ) -> {all.addAll(item); return all;});
			String ids = athleteIdList.stream().collect(Collectors.joining(","));
			Map<String,Object> map = new HashMap<>();
			map.put("ids", ids);
			list = (List<AthleteInfo>) dao.findForList("AthleteInfoMapper.findAthleteList", map);
		} catch (Exception e) {
			e.printStackTrace();
			list = new ArrayList<>();
		}
		return list;
	}
	/**
	 *
	 * @Description:查询对应群体下的时间节点
	 * @param pid
	 * @return List<String>
	 */
	@SuppressWarnings("unchecked")
	public List<String> findTimes(Integer cid){
		List<String> list = null;
		try {
			Map<String, Object> map = new HashMap<>();
			map.put("cid", cid);
			map.put("matchId", Constants.matchId);
			list = (List<String>) dao.findForList("GroupMapper.findTimes", map);
		} catch (Exception e) {
			list = new ArrayList<>();
			e.printStackTrace();
		}
		return list;
	}
	/**
	 *
	 * @Description:运动员参赛信息
	 * @param cid
	 * @return List<MatchAthlete>
	 */
	@SuppressWarnings("unchecked")
	public List<Map<String, Object>> findMatchByAthleteid(Integer cid){
		List<Map<String, Object>> list = null;
		try {
			Map<String, Object> map = new HashMap<>();
			map.put("cid", cid);
			map.put("matchId", Constants.matchId);
			list = (List<Map<String, Object>>) dao.findForList("AthleteInfoMapper.findMatchByAthleteid", map);
		} catch (Exception e) {
			list = new ArrayList<>();
			e.printStackTrace();
		}
		return list;
	}
	/**
	 *
	 * @Description:运动员信息
	 * @param cid
	 * @return AthleteInfo
	 */
	public AthleteInfo findAthleteInfo(Integer cid){
		AthleteInfo bean = null;
		try {
			bean = (AthleteInfo) dao.findForObject("AthleteInfoMapper.findAthleteInfo",cid);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return bean;
	}

	/**
	 * 运动员参赛名次信息
	 * @param cid
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<Map<String, Object>> althleteResultInfo(Integer cid) {
		List<Map<String, Object>> list = null;
		try {
			Map<String, Object> map = new HashMap<>();
			map.put("cid", cid);
			map.put("matchId", Constants.matchId);
			list = (List<Map<String, Object>>) dao.findForList("AthleteInfoMapper.findResultByAthleteid", map);
		} catch (Exception e) {
			list = new ArrayList<>();
			e.printStackTrace();
		}
		return list;
	}


	public Map<Integer, List<String>> getTimeFromColStu(String tClass) {
		Map<Integer, List<String>> map = new HashMap<>();
		try {
			Map<String, Object> param = new HashMap<>();
			param.put("tClass", tClass);
			param.put("matchId", Constants.matchId);
			List<String> dateTimeList = (List<String>) dao.findForList("MatchMapper.getTimeFromColStu", param);
			for (String s : dateTimeList) {
				if(!StringUtils.isBlank(s)){
					String ts[] = s.split("-");
					if(map.containsKey(Integer.parseInt(ts[1]))){
						List<String> list1 = map.get(Integer.parseInt(ts[1]));
						list1.add(s);
					}else{
						List<String> list2 = new ArrayList<String>();
						list2.add(s);
						map.put(Integer.parseInt(ts[1]), list2);
					}
				}
			}
			Set<Map.Entry<Integer, List<String>>> entries = map.entrySet();
			Iterator<Map.Entry<Integer, List<String>>> iterator = entries.iterator();
			while (iterator.hasNext()){
				Map.Entry<Integer, List<String>> next = iterator.next();
				Object[] array = next.getValue().toArray();
				Arrays.sort(array, new Comparator<Object>() {
					@Override
					public int compare(Object o1, Object o2) {
						Integer c1 = Integer.parseInt(((String)o1).split("-")[2]);
						Integer c2 = Integer.parseInt(((String)o2).split("-")[2]);
						return c1-c2;
					}
				});

				List<String> newValue = new ArrayList<>();
				for (Object o : array) {
					newValue.add((String) o);
				}
				next.setValue(newValue);
			}

			System.err.println("dateTimeList = " + dateTimeList);


		} catch (Exception e) {
			e.printStackTrace();
		}
		return map;
	}

	public List<Match> findMatchByTimeForzdxs(String time,String tClass) {
		List<Match> list = null;
		try {
			Map<String, Object> map = new HashMap<>();
			map.put("time", time);
			map.put("tClass", tClass);
			map.put("matchId", Constants.matchId);
			list = (List<Match>) dao.findForList("MatchMapper.findMatchByTimeForzdxs",map);
		} catch (Exception e) {
			e.printStackTrace();
			list = new ArrayList<>();
		}
		return list;
	}

	public List<Match> findMatchByParamForzdxs(String time, String classAllName) {

		Map<String, Object> map = new HashMap<>();
		map.put("time", time);
		map.put("classAllName", classAllName);
		map.put("matchId", Constants.matchId);
		List<Match> list = null;
		try {
			list = (List<Match>) dao.findForList("MatchMapper.findMatchByParamForzdxs",map);
		} catch (Exception e) {
			e.printStackTrace();
			list = new ArrayList<>();
		}
		return list;
	}




	public List<ThreeMetaData> query12WithAccountType() throws Exception {
		Map<String, Object> map = new HashMap<>();
		map.put("matchId", Constants.matchId);
		List<ThreeMetaData> forList = (List<ThreeMetaData>) dao.findForList("MatchMapper.query12WithAccountType", map);
		Iterator<ThreeMetaData> iterator = forList.iterator();
		while (iterator.hasNext()){
			ThreeMetaData next = iterator.next();
			if (next.getUnitName()==null) {
				iterator.remove();
			}
		}
		Collections.sort(forList, new Comparator<ThreeMetaData>() {
			@Override
			public int compare(ThreeMetaData a, ThreeMetaData b) {

				if ((a.getFirst()).equals(b.getFirst())) {
					if (( a.getSecond()).equals(b.getSecond())) {
						return Integer.parseInt(b.getThree()) - Integer.parseInt(a.getThree());
					}
					return Integer.parseInt(b.getSecond()) - Integer.parseInt(a.getSecond());
				}
				return  Integer.parseInt(b.getFirst()) - Integer.parseInt(a.getFirst());
			}
		});
		return forList;
	}

	public List<FindOrderVO> queryTeenagersThreeList(Integer pid, Integer account) throws Exception {
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("pid",pid);
		params.put("accountType",account);
		params.put("matchId", Constants.matchId);
		List<FindOrderVO> forList = (List<FindOrderVO>) dao.findForList("MatchMapper.queryTeenagersThreeList", params);
		Collections.sort(forList, new Comparator<FindOrderVO>() {
			@Override
			public int compare(FindOrderVO a, FindOrderVO b) {
				int jpCount1 =  b.get金牌();
				int jpCount2 = a.get金牌();
				if(jpCount1==jpCount2){
					int ypCount1 = b.get银牌();
					int ypCount2 =  a.get银牌();
					if(ypCount1==ypCount2){
						int tpCount1 = b.get铜牌();
						int tpCount2 = a.get铜牌();
						if(tpCount1==tpCount2){
							float integralCount1 = b.get总分();
							float integralCount2 = a.get总分();
							return (int) (integralCount1 - integralCount2);
						}
						return tpCount1-tpCount2;
					}
					return ypCount1-ypCount2;
				}
				return jpCount1 - jpCount2;
			}
		});

		return forList;
	}
}
